﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Threading;

namespace ZMHWcfServiceLibrary
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码和配置文件中的类名“MyDuplexContract”。
    public class MyDuplexContract : IMyDuplexContract, IDisposable
    {
        static List<IMyDuplexContractCallback> m_Callbacks = new List<IMyDuplexContractCallback>();
        public static void CallClients()
        {
            Action<IMyDuplexContractCallback> invoke = delegate (IMyDuplexContractCallback callback) { callback.OnCallback(); };
            m_Callbacks.ForEach(invoke);
        }
        Thread th_test;
        public MyDuplexContract()
        {
            th_test = new Thread(new ThreadStart(() =>
            {
                while (true)
                {
                    Thread.Sleep(1000);
                    if (read)
                    {
                        read = false;
                        Trace.WriteLine(callback.OnCallback());
                    }
                }
            }));
            th_test.Start();
        }
        bool read = false;
        public void Dispose()
        {
            th_test.Start();
        }
        public void Connect()
        {
            IMyDuplexContractCallback callback = OperationContext.Current.GetCallbackChannel<IMyDuplexContractCallback>();
            if (m_Callbacks.Contains(callback) == false) m_Callbacks.Add(callback);
        }

        public void Disconnect()
        {
            IMyDuplexContractCallback callback = OperationContext.Current.GetCallbackChannel<IMyDuplexContractCallback>();
            if (m_Callbacks.Contains(callback) == true) m_Callbacks.Remove(callback);
            else throw new InvalidOperationException("Cannot find callback");
        }
        IMyDuplexContractCallback callback;
        public void DoWork()
        {
            callback = OperationContext.Current.GetCallbackChannel<IMyDuplexContractCallback>();
            if (m_Callbacks.Contains(callback) == false) m_Callbacks.Add(callback);
            Trace.WriteLine("MyDuplexContract!"); 
            read = true;
        }
    }
}
